package com.shiguiwu.springmybatis.app.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

/**
 * @description: 异常拦截
 * @author: stone
 * @date: Created by 2023/3/6 21:03
 * @version: 1.0.0
 * @pakeage: com.shiguiwu.springmybatis.app.controller
 */
@RestControllerAdvice
@Slf4j
public class MyExceptionHandler {


    @ExceptionHandler(MethodArgumentNotValidException.class)
    public String handle(MethodArgumentNotValidException e) {
        log.info("e1 ===> {}",e.getMessage());
        return e.getBindingResult().getFieldError().getDefaultMessage();
    }


    @ExceptionHandler(BindException.class)
    public String handle(BindException e) {
        //e.printStackTrace();
        log.info("e2 ===> {}",e.getMessage());
        return e.getBindingResult().getFieldError().getDefaultMessage();
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public String handle(ConstraintViolationException e) {
        //e.printStackTrace();
        log.info("e3 ===> {}",e.getMessage());
        StringBuffer sb = new StringBuffer();
        for (ConstraintViolation<?> violation : e.getConstraintViolations()) {
            sb.append(violation.getMessage());
        }
        return sb.toString();

    }
}
